package cnrpc

import (
	"fmt"

	eclient "go.etcd.io/etcd/client/v3"
	eresolver "go.etcd.io/etcd/client/v3/naming/resolver"
	"google.golang.org/grpc"
	"google.golang.org/grpc/balancer/roundrobin"
	"google.golang.org/grpc/credentials/insecure"
)

type (
	Client struct {
		EtcdURL     string //etcd的访问地址
		ServiceName string //服务地址
	}
)

func NewClient(etcdURL, serviceName string) *Client {
	client := new(Client)
	client.EtcdURL = etcdURL
	client.ServiceName = serviceName
	return client
}

func (client *Client) Conn() (conn *grpc.ClientConn, err error) {
	//创建etcd的客户端
	etcdClient, err := eclient.NewFromURL(client.EtcdURL)
	if err != nil {
		return
	}
	//创建etcd实现的grpc服务注册模块
	etcdResolverBuilder, err := eresolver.NewBuilder(etcdClient)
	if err != nil {
		return
	}
	// 拼接服务名称，需要固定义 etcd:/// 作为前缀
	etcdTarget := fmt.Sprintf("etcd:///%s", client.ServiceName)

	// 创建 grpc 连接代理
	conn, err = grpc.Dial(
		// 服务名称
		etcdTarget,
		// 注入 etcd resolver
		grpc.WithResolvers(etcdResolverBuilder),
		// 声明使用的负载均衡策略为 roundrobin
		grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	return
}
